package com.hlw.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hlw.core.TreeTableModel;
import com.hlw.core.TreeTableSelect;
import com.hlw.dao.MenuMapper;
import com.hlw.dao.RoleMapper;
import com.hlw.entity.Menu;
import com.hlw.entity.Role;
import com.hlw.entity.User;
import com.hlw.service.IMenuService;
import com.hlw.service.IRoleService;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author Mht
 * @since 2020-05-02
 */
@Controller
@RequestMapping("/menu")
public class MenuController {
	@Resource
	private MenuMapper mapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private IRoleService roleService;
	
	@Resource
	private IMenuService navigationService;

	@RequestMapping("/findMenu")
	@ResponseBody
	public Map<String, Object> findMenu() {
     User user = (User) SecurityUtils.getSubject().getPrincipal();
     Integer rid = roleMapper.findRoleByUid(user.getId());//获取用户角色
     Role rlist =roleService.selectById(rid);
     System.out.println("查询的集合为："+roleMapper.findRoleById(user.getId()));
   
    	if(rlist.getName().equals("admin")){
    		 System.out.println("当前用户登陆角色为："+rlist);
    			Map<String, Object> data = navigationService.findMenu();
    			return data;
    	}else{
            List<Menu> menuList = mapper.findPermissionByRoleId(rlist.getId());//获取用户权限
            Map<String,Object> data = new HashMap<>();
            List<Menu> newMenuList = new ArrayList<>();
            if(menuList.size()!=0){
            for(int k = 0; k < menuList.size(); k++){
            	Menu menu = menuList.get(k);
                List<Menu> childMenuList = new ArrayList<>();
                
                if(menu.getPid()==0){
                	for (int j = 0; j < menuList.size(); j++) {
                        if (Objects.equals(menu.getId(), menuList.get(j).getPid())) {
                            childMenuList.add(menuList.get(j));
                        }
                    }
                    menu.setChildrens(childMenuList);
                    newMenuList.add(menu); 
                }             	
                
	        
	        data.put("menu",newMenuList);
	        return data;
	        }
    	}
    	
    	}
	return null;
	
    
	}
	
	
	
	@RequestMapping("getAll")
	public List<Menu> findAll() {
		System.out.println(navigationService.findAll());
		return navigationService.findAll();
	}
	
	@RequestMapping(value="menulist",method=RequestMethod.GET)
	public String menuList(Model model) {
		//获取当前用户，只有角色为admin的才有权限曾删改查
	     User user = (User) SecurityUtils.getSubject().getPrincipal();
	    Integer rid= roleMapper.findRoleByUid(user.getId());
		Role role = roleService.selectById(rid);
		model.addAttribute("userRole", role.getName());
		return "/system/menu/menulist";	
		}
	
	@RequestMapping(value="treeSelect")
	@ResponseBody
	public Object treeSelect()  {
		  List<Menu> menus =  navigationService.findAll();
		  List<Object> list = new ArrayList<>();
	        for (Menu m : menus) {

	            if(m.getPid()==0){//判断是否是一级菜单
	               boolean flag;
	                if(m.getDel_flag()==1){
	                flag=false;
	                }else{
	                    flag=true;
	                }
	                JSONObject treeObject = new JSONObject();
	                
	                 treeObject.put("id", m.getId());
	                 treeObject.put("name", m.getName());//tree的节点名称
	                 treeObject.put("open", true);
	                 treeObject.put("children", getChildren(m.getId(),menus));//孩子节点，递归遍历
	                 list.add(treeObject);
	           }
	         }
	         return list;
		
	}

	
public List<Object> getChildren(Integer parentId,List<Menu> menus){
    List<Object> list = new ArrayList<>();
        for (Menu m : menus) {
            if(m.getPid().equals(parentId)){
                boolean flag;
                if(m.getDel_flag()==1){
                    flag=false;
                }else{
                    flag=true;
                }
            JSONObject obj = new JSONObject();
            obj.put("id", m.getId());
            obj.put("name", m.getName());
            obj.put("open", false);
            obj.put("children", getChildren(m.getId(),menus));
            list.add(obj);
        }
    }
    return list;
}
	/**
	 * layui treeTable 菜单列表数据获取
	 * @return
	 */
	
	@RequestMapping(value="treeList")
	@ResponseBody
	public Object findTypeTree()  {
		  List<Menu> menus =  navigationService.findAll();
		  List<Object> list = new ArrayList<>();
	        for (Menu m : menus) {
	           
	                JSONObject treeObject = new JSONObject();
	                if(m.getPid()==1){
	                    treeObject.put("spread", true);//是否直接展开
	                }
	                 treeObject.put("id", m.getId());
	                 treeObject.put("pid", m.getPid());
	                 treeObject.put("name", m.getName());//tree的节点名称
	                 treeObject.put("menuurl", m.getUrl());
	                 treeObject.put("issys", m.getIssys());
	                 treeObject.put("indexmenu", m.getIndexmenu());
	                 list.add(treeObject);
	           }
	         
	         return new TreeTableModel(list);
		
	}

	/**
	 * layui treeTable 菜单列表数据获取
	 * @return
	 */
	
	/*@RequestMapping(value="treeSelect")
	@ResponseBody
	public Object treeSelect()  {
		  List<Menu> menus =  navigationService.findAll();
		  List<Object> list = new ArrayList<>();
	        for (Menu m : menus) {
	           
	                JSONObject treeObject = new JSONObject();
	                if(m.getPid()==1){
	                    treeObject.put("spread", true);//是否直接展开
	                }
	                 treeObject.put("id", m.getId());
	                 treeObject.put("pid", m.getPid());
	                 treeObject.put("name", m.getName());//tree的节点名称
	                 treeObject.put("menuurl", m.getUrl());
	                 treeObject.put("indexmenu", m.getIndexmenu());
	                 list.add(treeObject);
	           }
	         
	         return new TreeTableModel(list);
		
	}
	
	
*/
	/**
	 * 加载新增修改菜单的下拉框
	 * @param model
	 * @param id
	 * @return
	 
	@RequestMapping(value = "menuSelect", method = RequestMethod.GET)
	@ResponseBody
	public Object checkMenu() {
		List<Menu> menu = navigationService.findAll();
		List<Object> list = new ArrayList<>();
		for (Menu menus : menu) {
			if (menus.getPid() == 0) {
				list.add(menus);
			}

		}
		return list;
	}
*/
	/**
	 * 根据ID修改菜单
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="editMenu",method=RequestMethod.GET)
	public String editMenu(org.springframework.ui.Model model,String id) {
		if(id!=null){
			Menu menu= navigationService.findMenuById(id);
			model.addAttribute("menus", menu);			
		}
		
		return "/system/menu/menu_edit";	
		}
	
	/**
	 * 新增菜單頁面
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="addMenu",method=RequestMethod.GET)
	public String addMenu() {
		return "/system/menu/menu_add";	
		}
	
	/**
	 * 保存菜单
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="saveMenu",method=RequestMethod.POST)
	@ResponseBody
	public String innserMenu(@ModelAttribute("menus")Menu menu) {
		if(menu.getId()==null){
			if(menu.getPid()==null){
				menu.setPid(0);	
			}
			mapper.insert(menu);
			return "success";
		}else{
			mapper.updateAllColumnById(menu);
			return "success";
			
		}
		 		
	}
	/**
	 * 保存菜单
	 * @param model
	 * @param id
	 * @return
	 *//*
	@RequestMapping(value="updateMenu",method=RequestMethod.POST)
	@ResponseBody
	public String updateMenu(@ModelAttribute("menus")Menu menu) {
		mapper.updateAllColumnById(menu);
		return "success";
		
		 		
	}*/
	/**
	 * 根据ID修改菜单
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="delMenu",method=RequestMethod.POST)
	@ResponseBody
	public String deleteMenu(Integer id) {
		List<Menu> menus =navigationService.findAll();
		Menu menu =mapper.selectById(id);
		//获取到的menuID若为父级菜单将删除该ID下的所有子级和权限
		if(menu.getPid().equals(0)){
			for(int i =0;i<menus.size();i++){
				if(menus.get(i).getPid()==menu.getId()){
					mapper.deleteById(menus.get(i).getId());
					mapper.deletePerByMid(menus.get(i).getId());	
				}
				mapper.deleteById(id);
				mapper.deletePerByMid(id);	

			}
		}else{
			mapper.deleteById(id);
			mapper.deletePerByMid(id);
			
		}				
		return "success";
		
		 		
	}
	
	
	@RequestMapping(value="layuiTree")
	@ResponseBody
	public Object layuitree()  {
		  List<Menu> menus =  navigationService.findAll();
		  List<Object> list = new ArrayList<>();
	        for (Menu m : menus) {

	            if(m.getPid()==0){//判断是否是一级菜单
	               boolean flag;
	                if(m.getDel_flag()==1){
	                flag=false;
	                }else{
	                    flag=true;
	                }
	                JSONObject treeObject = new JSONObject();
	                 treeObject.put("id", m.getId());
	                 treeObject.put("title", m.getName());//tree的节点名称
	                 treeObject.put("spread", true);
	                 treeObject.put("field", m.getName());
	                 treeObject.put("children", getChildrenTree(m.getId(),menus));//孩子节点，递归遍历
	                 list.add(treeObject);
	           }
	         }
	         return  list;
		
	}

	
public List<Object> getChildrenTree(Integer parentId,List<Menu> menus){
   List<Object> list = new ArrayList<>();
   /*    List<Menu> plist = mapper.findPermissionByRoleId(rid);//获取用户权限
*/
        for (Menu m : menus) {
            if(m.getPid().equals(parentId)){
                boolean flag;
                if(m.getDel_flag()==1){
                    flag=false;
                }else{
                    flag=true;
                }
            JSONObject obj = new JSONObject();
            obj.put("id", m.getId());
            obj.put("title", m.getName());//tree的节点名称
            obj.put("field", m.getName());
				/*  for(int i=0;i<plist.size();i++){
			     	 if(plist.get(i).getId().equals(m.getId()))
			     		obj.put("checked", true);
			
			      
				
			}*/
      	
            obj.put("children", getChildren(m.getId(),menus));
            list.add(obj);
        }
    }
    return list;
}


}

	

